//
//  ZPMineChangeStuViewController.m
//  ZPIOSEducation
//
//  Created by 李伟 on 2016/12/4.
//  Copyright © 2016年 mini1. All rights reserved.
//

#import "ZPMineChangeStuViewController.h"
#import "ZPRegisterInformationViewController.h"

#import "ZPMineChangeStuTitleCell.h"
#import "ZPMineChangeStuCell.h"

@interface ZPMineChangeStuViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSMutableArray  *dataArray;
}

@property (weak, nonatomic) IBOutlet UITableView *mainTableView;

@end

@implementation ZPMineChangeStuViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"切换学生";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"zhenpin_back"] style:UIBarButtonItemStylePlain target:self action:@selector(navLeftButtonClick)];
    [[NSNotificationCenter  defaultCenter] addObserver:self selector:@selector(refreshStudentList) name:@"refreshStudentList" object:nil];
    
    self.mainTableView.delegate = self;
    self.mainTableView.dataSource = self;
    
    dataArray = [[NSMutableArray  alloc] init];
    [self  requestData];
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)refreshStudentList
{
    [self  requestData];
}

#pragma mark - Button Actions
#pragma mark 导航栏左边按钮
- (void)navLeftButtonClick
{
    [self.navigationController  popViewControllerAnimated:YES];
}

#pragma mark 新建学生信息按钮
- (IBAction)creatStuInfo:(id)sender
{
    if([dataArray count]  >= 8){
        [ZPPromptView showMessage:@"最多只能添加8个学生"];
        return;
    }
    ZPRegisterInformationViewController  *viewController = [[ZPRegisterInformationViewController alloc] initWithNibName:@"ZPRegisterInformationViewController" bundle:nil];
    [self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark - 网络相关
- (void)requestData
{
    NSDictionary  *paramDic = [NSDictionary  dictionaryWithObjectsAndKeys:[[ZPAuthStore  sharedZPAuthStore].userToDic  objectForKey:@"memberId"],@"memberId", nil];
    [self  showHudithString:@"加载中..."];
    [[ZPNetworking  sharedZPNetworking] POST:APIUC@"user/getStudentByMemberId.json" parameters:paramDic progress:^(NSProgress * _Nullable progress) {
        
    } success:^(id  _Nonnull responseObject) {
        NSLog(@"======%@",responseObject);
        [self  hiddenHud];
        
        if ([[responseObject  objectForKey:@"code"] integerValue] == 200) {
            if ([[[responseObject  objectForKey:@"result"] objectForKey:@"student"] isKindOfClass:[NSArray  class]]) {
                [dataArray  removeAllObjects];
                [dataArray  addObjectsFromArray:[[responseObject  objectForKey:@"result"] objectForKey:@"student"]];
                [self.mainTableView  reloadData];
            }
            
        }else {
            [ZPPromptView  showMessage:[responseObject  objectForKey:@"codeMsg"]];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self  hiddenHud];
        
    }];
}

- (void)requestStuInfoWithIndex:(NSInteger)index
{
    NSDictionary  *tempDic = [dataArray  objectAtIndex:index];
    NSDictionary  *paramDic = [NSDictionary  dictionaryWithObjectsAndKeys:[NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"id"]],@"id", nil];
    [self  showHudithString:@"发送中..."];
    [[ZPNetworking  sharedZPNetworking] POST:APIUC@"user/getStudentById.json" parameters:paramDic progress:^(NSProgress * _Nullable progress) {
        
    } success:^(id  _Nonnull responseObject) {
        NSLog(@"======%@",responseObject);
        [self  hiddenHud];
        
        if ([[responseObject  objectForKey:@"code"] integerValue] == 200) {
            NSDictionary  *resultDic = [responseObject  objectForKey:@"result"];
            
            NSString *homePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/UserInfo.plist"];
            NSMutableDictionary *dataDic = [[NSDictionary dictionaryWithContentsOfFile:homePath] mutableCopy];
            [dataDic  setObject:[NSString  stringWithFormat:@"%@",[resultDic  objectForKey:@"grade"]] forKey:@"grade"];
            [dataDic  setObject:[NSString  stringWithFormat:@"%@",[resultDic  objectForKey:@"headUrl"]] forKey:@"headUrl"];
            [dataDic  setObject:[NSString  stringWithFormat:@"%@",[resultDic  objectForKey:@"name"]] forKey:@"stuName"];
            [dataDic  setObject:[NSString  stringWithFormat:@"%@",[resultDic  objectForKey:@"stuId"]] forKey:@"stuId"];
            [dataDic  setObject:[NSString  stringWithFormat:@"%@",[resultDic  objectForKey:@"stuNumber"]] forKey:@"stuNum"];
            [dataDic  writeToFile:homePath atomically:YES];
            
            [[ZPAuthStore sharedZPAuthStore] resetUserInfoDictionary];
            [[ZPAuthStore sharedZPAuthStore] setWebViewCookiesWithType:1];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"logOnNotification" object:nil];
            [self.navigationController  popViewControllerAnimated:YES];
            
        }else {
            [ZPPromptView  showMessage:[responseObject  objectForKey:@"codeMsg"]];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self  hiddenHud];
        
    }];
}

#pragma mark - UITableView Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [dataArray  count] + 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 34.;
    } else {
        return 66.;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger  row = [indexPath  row];
    if (row == 0) {
        static NSString *CellIdentifier = @"ZPMineChangeStuTitleCell";
        ZPMineChangeStuTitleCell  *cell = (ZPMineChangeStuTitleCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"ZPMineChangeStuTitleCell" owner:self options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        return cell;
    }else {
        static NSString *CellIdentifier = @"ZPMineChangeStuCell";
        ZPMineChangeStuCell  *cell = (ZPMineChangeStuCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"ZPMineChangeStuCell" owner:self options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        NSDictionary  *tempDic = [dataArray  objectAtIndex:row - 1];
        cell.nameLab.text = [NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"name"]];
        
        return cell;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger  row = [indexPath  row];
    if (row != 0) {
        [self  requestStuInfoWithIndex:row - 1];
    }
}

- (void)dealloc
{
    [[NSNotificationCenter  defaultCenter] removeObserver:self name:@"refreshStudentList" object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
